--#include "data\config\Fuben\MagicCityConfig.lua" once   --魔域迷城

MAGICCITY_FUBEN_SCENEID		= 0
MAGICCITY_FUBEN_KILLMONNUM	= 1



MAGICCITY_MY_MAX_STAR  	= 1 			--某关卡通关最大评分
MAGICCITY_MY_PASS_TIME 	= 2				--某关卡上次通关时间
MAGICCITY_MY_PASS_SCORE = 3				--某关卡上次通关评分
MAGICCITY_MY_DONE_TIMES = 4				--某关卡今日已经进入的次数
MAGICCITY_MY_BUY_TIMES  = 5				--某关卡已经购买的次数
MAGICCITY_MY_FIRSTFULLPASS  = 6			--某关卡是否已经领取三星通关奖励


MAGICCITY_OWNER_ID  		= 1 		--某关楼主ID
MAGICCITY_OWNER_NAME 		= 2			--某关楼主名称
MAGICCITY_OWNER_PASS_TIME  	= 3 		--某关楼主通关时间


MagicCityWeekRankColumn = 
{	
	{"name"},				--0，玩家Name
	{"serverId"},			--1，玩家ServerId(留空)
	{"job"},				--2，玩家职业
}

MagicCityWeekRank 		= Lang.Rank.MagicCityWeekRank			--魔域迷城周榜
MagicCityWeekLastRank 	= Lang.Rank.MagicCityWeekLastRank		--魔域迷城上周榜


function GmDoMagicCity( sysarg, flag, param )
	print("GmDoMagicCity, flag="..flag..", param="..param)
	if flag == 1 then
	elseif flag ==2 then
		MagicCityActorDailyProc( sysarg )
	elseif flag == 3 then
		SendCommonRankAwards( enCommonRankType_MagicCityWeek ) 			--周榜发奖
	elseif flag == 4 then
		SendMagicCityOwnerAwards()					--每日楼主奖励
	end
end


function InitMagicCityWeekRank()
	--print("*****>>InitMagicCityWeekRank...")
	Rank.Init(MagicCityWeekRank, MagicCityWeekRank, MagicCityWeekRankColumn, 1500, 0)
	--Rank.Init(MagicCityWeekLastRank, MagicCityWeekLastRank, MagicCityWeekRankColumn, 1500, 0)
end

--[[
注册一些事件
]]
function ResisterMagicCityProc()
	--print("ResisterMagicCityProc...")
	for cityIdx, cityCfg in ipairs( MagicCityCfg.cities ) do
		SceneHandExitDispatcher.register( cityCfg.sceneId,  OnHandExitMagicCity )			--注册离开场景、副本后触发的事件
		FubenTimeoutDispatcher.register( cityCfg.fubenId, OnMagicCityTimeout )				--注册场景、副本时间到后触发的事件
		SceneLogoutDispatcher.register( cityCfg.sceneId, OnLogoutnMagicCity )				--注册场景、副本中下线触发的事件
	end
end


--[[
副本时间到
]]
function OnMagicCityTimeout( fubenPtr )
	local fubenId = Fuben.getFuBenId(fubenPtr)
	--print("OnMagicCityTimeout, fubenId="..fubenId)
	local cityCfg = GetMagicCityCfgByFubenId( fubenId )
	if not cityCfg then
		return
	end

	local actorId 	= Fuben.getOwnerId( fubenPtr )
	local actorPtr 	= Actor.getActorById( actorId )
	--print("OnMagicCityTimeout, actorId="..actorId)
	if actorPtr and IsInMagicCityFuben( actorPtr ) then
		local fubenHandle	 = Fuben.getFubenHandle(fubenPtr)
		local GetBossNumFunc = MagicCityGetMonsterNumFunc( cityCfg )
		local allBoss, killBoss, allMon, killMon = GetBossNumFunc( fubenHandle )
		if killBoss + killMon < allBoss + allMon then
			OnMagicCityOver( actorPtr, cityCfg, 0 ) 			--通关失败
		end
	end
end

--[[
个人BOSS副本中下线
]]
function OnLogoutnMagicCity( sysarg )
	local sceneId 	= Actor.getSceneId( sysarg )
	local fubenPtr 	= Actor.getFubenPrt(sysarg)
	local fubenId 	= Fuben.getFuBenId(fubenPtr)

	--print("OnLogoutnMagicCity, sceneId="..sceneId..", fubenId="..fubenId)
	DroplineSaveFubenHandler( sysarg )

	local actorId 	= Actor.getActorId( sysarg )
	local actorName	= Actor.getName( sysarg )
	local sceneId 	= Actor.getSceneId( sysarg )
	local fubenId 	= Actor.getFubenId( sysarg )
	System.sendCommonLog( GameLog.clFubenDropReset_Logout, actorId, actorName , 0, sceneId, fubenId,'','',"fuben logout")
end

--[[
副本中恢复上线
]]
function ProcLoginMagicCity( sysarg, fubenPtr  )
	--print("ProcLoginMagicCity...")
	if not fubenPtr then
		return
	end

	local fubenId  = Fuben.getFuBenId( fubenPtr )
	--print("ProcLoginMagicCity, fubenId="..fubenId)
	local cityCfg  = GetMagicCityCfgByFubenId( fubenId )
	if not cityCfg then
		return
	end

	if fubenId ~= cityCfg.fubenId then 			--以正式副本为准
		return
	end

	local actorId 	= Actor.getActorId( sysarg )
	local actorName	= Actor.getName( sysarg )
	System.sendCommonLog( GameLog.clFubenDropReset_LoginTry, actorId, actorName , 0, 0, fubenId,'','', "magiccity login" )

	
	local fubenHandle = Fuben.getFubenHandle( fubenPtr )
	--print("ProcLoginMagicCity, fubenHandle="..fubenHandle)
	if fubenHandle <= 0 then
		return
	end

	if not Fuben.isFubenExist( fubenHandle ) then			--副本已经不存在（被撤销）了
		return
	end

	--这里预防曾经有某玩家保存的副本handle正好与此副本相同的情况
	local actorId = Actor.getActorId( sysarg )
	local ownerId = Fuben.getOwnerId( fubenPtr )			--副本Owner
	--print("ProcLoginMagicCity, actorId="..actorId..", ownerId="..ownerId)
	if actorId ~= ownerId then
		return
	end

	local enterPos = nil
	if cityCfg.enterPos then
		enterPos = cityCfg.enterPos
	elseif cityCfg.enterPosRand then
		local idx, randPos = GetItemIdxRandNoWeight( cityCfg.enterPosRand )
		enterPos = randPos
	end

	if not enterPos then
		return
	end

	if cityCfg.cityType == 3 then
		local babyNum = System.getMonsterCountById( cityCfg.baby.monsterId, cityCfg.sceneId, fubenHandle )
		--print("ProcLoginMagicCity, babyNum="..babyNum)
		if babyNum < 1 then
			OnMagicCityOver( sysarg, cityCfg, 0 ) 			--没有宝宝，通关失败，直接不用进入副本了
			Fuben.setFubenTime( fubenHandle, 1 )			--关闭副本，不用进入了
			return
		end
	end
	
	if Actor.enterFuBen(sysarg, fubenHandle, cityCfg.sceneId, enterPos[1], enterPos[2]) then
		InitMagicCityPanel( sysarg, cityCfg, false )
		System.sendCommonLog( GameLog.clFubenDropReset_LoginOk, actorId, actorName , 0, cityCfg.sceneId, fubenId,
			'', '', "magiccity login ok" )
	end
end

--[[
每周一零点处理
]]
function MagicCityMondayProc()
	--SendCommonRankAwards( enCommonRankType_MagicCityWeek, MagicCityCfg.weekRank ) 			--周榜发奖
	SendCommonRankAwards( enCommonRankType_MagicCityWeek ) 										--周榜发奖
end

--[[
每天零点处理
]]
function MagicCityDailyProc()
	SendMagicCityOwnerAwards()					--每日楼主奖励
end



--[[
跨天数据重置
]]
function MagicCityActorDailyProc( sysarg )
	--print("MagicCityActorDailyProc...")
	for cityIdx, cityCfg in ipairs( MagicCityCfg.cities ) do 			--进入次数清0
		SetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_DONE_TIMES, 0 )
		SetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_BUY_TIMES, 0 )				--购买次数也清0，必须当天买当天用完
	end
	SendMagicCityMyEnterTimes( sysarg )
end

--[[
手工离开场景
1、手工离开，如果怪物没有击杀完毕，算通关失败
]]
function OnHandExitMagicCity( sysarg )
	--print("OnHandExitMagicCity")
	local sceneId = Actor.getSceneId( sysarg )
	local cityCfg = GetMagicCityCfgBySceneId( sceneId )
	if not cityCfg then
		return
	end

	local fubenPtr = Actor.getFubenPrt( sysarg )
	local fubenHandle = Fuben.getFubenHandle( fubenPtr )
	Fuben.setFubenTime( fubenHandle, 1 )				--手工离开，关闭副本

	local GetBossNumFunc = MagicCityGetMonsterNumFunc( cityCfg )
	local allBoss, killBoss, allMon, killMon = GetBossNumFunc( fubenHandle )
	if killBoss + killMon < allBoss + allMon then
		OnMagicCityOver( sysarg, cityCfg, 0 ) 			--通关失败
		Fuben.setFubenTime( fubenHandle, 1 )			--关闭副本
	end
end

function IsInMagicCityFuben( sysarg )
	local fubenId = Actor.getFubenId( sysarg )
	for cityIdx, cityCfg in pairs( MagicCityCfg.cities ) do
		if cityCfg.fubenId == fubenId then
			return true
		end
	end
	return false
end

--[[
魔域迷城
]]
function EnterMagicCity( sysarg, cityIdx )
	--print("EnterMayaPalace, palaceIdx="..palaceIdx)
	local cityCfg = GetMagicCityCfgByCityIdx( cityIdx )
	if not cityCfg then
		return
	end

	if cityIdx > 1 then
		local privCityIdx = cityIdx-1
		local privStar = GetMagicCityMyValue( sysarg, privCityIdx, MAGICCITY_MY_MAX_STAR )		--上一关的星级
		if privStar < 1 then
			Actor.sendTipmsg( sysarg, Lang.ScriptTips.MagicCity007, ttFlyTip )
			return
		end
	end

	if CommonEnterScence( sysarg,  cityCfg, GameLog.clMagicCityEnterFee, Lang.ScriptTips.MagicCityLog01,
		 MagicCityCheck, MagicCityBeforeEnter ) then
		InitMagicCityData( sysarg )

		local actorId 	= Actor.getActorId( sysarg )
		local fubenPtr 	= Actor.getFubenPrt( sysarg )
		Fuben.setOwnerId( fubenPtr, actorId )
		Fuben.setFbValue( fubenPtr, MAGICCITY_FUBEN_SCENEID, Actor.getSceneId(sysarg) )			--副本所属的场景ID
		MagicCityFreshMonster( sysarg, cityCfg )

		InitMagicCityPanel( sysarg, cityCfg, true )
		Actor.triggerAchieveEvent(sysarg, aAchieveEventFinishActivity, 12, 1)			--参加魔域迷城1次
		Actor.triggerQuestEvent(sysarg, 45, 8, 1) 										--任务事件-参加魔域迷城1次
	end
end

function InitMagicCityPanel( sysarg, cityCfg, isFirst )
	local panelInfo = {}
	panelInfo.title = Lang.ScriptTips.MagicCityName										--title
	panelInfo.subActivityId = cityCfg.cityIdx

	panelInfo.awardTitle = Lang.ScriptTips.panelCont06
	panelInfo.awards 	 = cityCfg.showAwards
	panelInfo.buttons  	 = {1}

	if isFirst then
		local totalMonNum 	= MagicCityGetMonsterTotelNum( cityCfg )		--获取
		local fubenPtr 		= Actor.getFubenPrt( sysarg )
		Fuben.setFbMonsterTotal( fubenPtr, totalMonNum ) 					--设置最大怪物数量
		Fuben.setKillMonsterCount( fubenPtr, 0 ) 							--设置击杀怪物数量为0
	end

	OpenCommonSpecialPanel( sysarg, 1, enRightPanelActivity_MagicCity, panelInfo, cityCfg, {1}, nil, MagicCityGetMonsterNumFunc( cityCfg ) )
end

function MagicCityGetMonsterNumFunc( cityCfg )
	--[[
	if cityCfg.cityType == 2 or cityCfg.cityType == 4 then
		return GetCommonBossMonsterNum5
	end
	return GetCommonBossMonsterNum3
	]]
	return GetCommonBossMonsterNum5
end

function MagicCityCheck( sysarg, cityCfg )
	--print("MagicCityCheck...")
	if not CheckActorDailyDoneTimes( sysarg, enDailyOpTimes_MagicCity, cityCfg.cityIdx ) then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0021,ttFlyTip)
		return false
	end
	return true
end

function MagicCityBeforeEnter( sysarg, cityCfg )
	--print("MagicCityBeforeEnter...")
	AddActorDailyDoneTimes( sysarg, enDailyOpTimes_MagicCity, cityCfg.cityIdx, 1 ) 				--进入次数+1
	--SendMagicCityMyData( sysarg, cityCfg.cityIdx )
	SendMagicCityMyEnterTimes( sysarg )
	return true
end

function InitMagicCityData( sysarg )
	local sVar = Actor.getStaticVar(sysarg)
	sVar.magicCityeEnterTime = System.getCurrMiniTime()
	if not sVar.magicCityData then
		sVar.magicCityData = {}
	end
end

function GetMagicCityCfgByCityIdx( cityIdx )
	return MagicCityCfg.cities[cityIdx]
end

function GetMagicCityCfgBySceneId( sceneId )
	for cityIdx, cityCfg in pairs( MagicCityCfg.cities ) do
		if cityCfg.sceneId == sceneId then
			return cityCfg
		end
	end
	return nil
end

function GetMagicCityCfgByFubenId( fubenId )
	for cityIdx, cityCfg in pairs( MagicCityCfg.cities ) do
		if cityCfg.fubenId == fubenId then
			return cityCfg
		end
	end
	return nil
end

function MagicCityGetMonsterTotelNum( cityCfg )
	local monNum = 0
	if cityCfg.cityType == 1 or cityCfg.cityType == 3 then
		for monIdx, monCfg in ipairs( cityCfg. monsters) do
			monNum = monNum + monCfg.num
		end
	elseif cityCfg.cityType == 2 then
		for monIdx, monCfg in ipairs( cityCfg. monsters) do
			for subMonIdx, subOneMon in ipairs( monCfg.mobMonsWenDie ) do
				monNum = monNum + subOneMon.num
			end
		end
	elseif cityCfg.cityType == 4 then
		monNum = cityCfg.monsterMaxNum				--随机抽取，只能配置
	end
	return monNum
end

--[[
迷幻魔宫-刷怪
]]
function MagicCityFreshMonster( sysarg, cityCfg )
	if cityCfg.cityType == 1 then
		MagicCityFreshMonster1( sysarg, cityCfg )
	elseif cityCfg.cityType == 2 then
		MagicCityFreshMonster2( sysarg, cityCfg )
	elseif cityCfg.cityType == 3 then
		MagicCityFreshMonster3( sysarg, cityCfg )
	elseif cityCfg.cityType == 4 then 
		MagicCityFreshMonster4( sysarg, cityCfg )
	end
end

function MagicCityFreshMonster1( sysarg, cityCfg )
	--print("MagicCityFreshMonster1...")
	local fubenPtr 		= Actor.getFubenPrt(sysarg)
	local fubenHandle 	= Fuben.getFubenHandle(fubenPtr)
	FreshCommonMonsters( cityCfg.monsters, fubenHandle, true )
end

function MagicCityFreshMonster2( sysarg, cityCfg )
	--print("MagicCityFreshMonster2...")
	local fubenPtr 		= Actor.getFubenPrt(sysarg)
	local fubenHandle 	= Fuben.getFubenHandle(fubenPtr)
	--FreshCommonMonsters( cityCfg.guards, fubenHandle, true )
	FreshCommonMonsters( cityCfg.monsters, fubenHandle, true )
	--[[
	local boardStr = Lang.ScriptTips.MagicCity006				--注意：字符串中要带有一个 %d
	OpenBoardPanel( sysarg, enBoardPanelStyle_CountDown1, boardStr, cityCfg.freshTimeAfterEnter )

	
	Fuben.unregScriptCallback(fubenPtr, "MagicCityFreshCity2Monster")
	local interval = cityCfg.freshTimeAfterEnter * 1000
	Fuben.regScriptTimer2S(fubenPtr, 0, interval, interval, 1, "MagicCityFreshCity2Monster")			--一段时间后，执行刷怪1次
	]]
end

function MagicCityFreshMonster3( sysarg, cityCfg )
	--print("MagicCityFreshMonster3...")
	local fubenPtr 		= Actor.getFubenPrt(sysarg)
	local fubenHandle 	= Fuben.getFubenHandle(fubenPtr)
	FreshCommonMonsters( cityCfg.monsters, fubenHandle, true )
	--FreshCommonMonsters( cityCfg.guards, fubenHandle, true )

	local hScene 	= Fuben.getSceneHandleById( cityCfg.sceneId, fubenHandle )
	local setPos 	= cityCfg.baby.pos
	local monster 	= Fuben.createMonster( hScene, cityCfg.baby.monsterId, setPos[1], setPos[2], 0 )
	if monster then
		Actor.followActor( monster, sysarg, 3, 12, true )  		--跟随某个玩家
	    Actor.setEntityTelByOwnderAttr( monster, true )     	--设置实体是否跟着归属者传送
	    Actor.setEntityLazyFollow( monster, true )          	--设置实体是否惰性跟随
		--print("MagicCityFreshMonster3, -> set Follow")
	end
end

function MagicCityFreshMonster4( sysarg, cityCfg )
	--print("MagicCityFreshMonster4...")
	local fubenPtr 		= Actor.getFubenPrt(sysarg)
	local fubenHandle 	= Fuben.getFubenHandle(fubenPtr)
	FreshCommonMonstersRand( cityCfg.monsters, fubenHandle, true, cityCfg.monsterFresh )
	FreshCommonMonsters( cityCfg.boss, fubenHandle, true )
end


--[[
刷出第二层的怪
]]
function MagicCityFreshCity2Monster( fubenPtr )
	local cityCfg = MagicCityCfg.cities[2]
	local fubenHandle 	= Fuben.getFubenHandle(fubenPtr)
	FreshCommonMonsters( cityCfg.monsters, fubenHandle, true )
end

--[[
--sysarg:归属玩家
--lastHitKiller：最后一击玩家
注意：怪物死亡时，玩家可能不在线，要确保副本进度能够继续进行
]]
function OnMagicCityMonsterDie( monster, sysarg, monId, lastHitKiller )
	local sceneId = Actor.getSceneId( monster )
	local cityCfg = GetMagicCityCfgBySceneId( sceneId )
	if not cityCfg then
		return
	end
	--print("OnMagicCityMonsterDie, monId="..monId..", cityIdx="..cityCfg.cityIdx)

	local fubenPtr = Actor.getFubenPrt( monster )				--怪物所在副本
	local fubenHandle = Fuben.getFubenHandle( fubenPtr )
	local GetBossNumFunc = MagicCityGetMonsterNumFunc( cityCfg )

	if cityCfg.cityType == 1 or cityCfg.cityType == 3 or cityCfg.cityType == 4 then
		Fuben.addKillMonsterCount( fubenPtr ) 					--副本击杀怪物数量++
	end

	--怪物死亡后，需要刷怪
	local monCfg = GetMagicCityMonsterCfg( cityCfg, monId )
	if monCfg and monCfg.mobMonsWenDie then
		FreshCommonMonsters( monCfg.mobMonsWenDie, fubenHandle, true )
	end

	local actorId 	= Fuben.getOwnerId( fubenPtr )
	local actorPtr 	= Actor.getActorById( actorId )
	--print("OnMagicCityMonsterDie, actorId="..actorId)
	if actorPtr and IsInMagicCityFuben( actorPtr ) then 			--玩家在线并且在副本中
		ChangeCommonSpecialPanel( actorPtr, cityCfg, {1}, {1}, nil, GetBossNumFunc )
		
		local allBoss, killBoss, allMon, killMon = GetBossNumFunc( fubenHandle )
		--print("OnMagicCityMonsterDie, allMon="..allMon..", killMon="..killMon)
		if allBoss + allMon > 0 and killBoss + killMon >= allBoss + allMon then
			OnMagicCityOver( actorPtr, cityCfg, 1 ) 			--通关成功
			Fuben.setFubenTime( fubenHandle, 1 )			--关闭副本
		end
	end
end

function GetMagicCityMonsterCfg( cityCfg, monId )
	for monIdx, monCfg in ipairs( cityCfg.monsters or {} ) do
		if monCfg.monsterId == monId then
			return monCfg
		end
	end
	return monCfg
end

--[[
击杀某怪后再召唤出来的怪死亡
]]
function OnMagicCitySubMonsterDie( monster, sysarg, monId, lastHitKiller )
	--print("OnMagicCitySubMonsterDie, monId="..monId)
	local sceneId = Actor.getSceneId( monster )
	local cityCfg = GetMagicCityCfgBySceneId( sceneId )
	if not cityCfg then
		return
	end

	local fubenPtr 		= Actor.getFubenPrt( monster )					--怪物所在副本
	local fubenHandle 	= Fuben.getFubenHandle( fubenPtr )
	Fuben.addKillMonsterCount( fubenPtr ) 							--副本击杀怪物数量++
	local GetBossNumFunc = MagicCityGetMonsterNumFunc( cityCfg )

	local actorId 	= Fuben.getOwnerId( fubenPtr )
	local actorPtr 	= Actor.getActorById( actorId )
	if actorPtr and IsInMagicCityFuben( actorPtr ) then 			--玩家在线并且在副本中
		ChangeCommonSpecialPanel( actorPtr, cityCfg, {1}, {1}, nil, GetBossNumFunc )
		
		local allBoss, killBoss, allMon, killMon = GetBossNumFunc( fubenHandle )
		--print("OnMagicCitySubMonsterDie, allMon="..allMon..", killMon="..killMon)
		if allBoss + allMon > 0 and killBoss + killMon >= allBoss + allMon then
			OnMagicCityOver( actorPtr, cityCfg, 1 ) 			--通关成功
			Fuben.setFubenTime( fubenHandle, 1 )				--关闭副本
		end
	end

end

--[[
需要保护的怪死亡
--sysarg:归属玩家
--lastHitKiller：最后一击玩家
]]
function OnMagicCityBabyDie( monster, sysarg, monId, lastHitKiller )
	--print("OnMagicCityBabyDie, monId="..monId)
	local sceneId = Actor.getSceneId( monster )
	local cityCfg = GetMagicCityCfgBySceneId( sceneId )
	if not cityCfg then
		return
	end
	--print("OnMagicCityBabyDie, monId="..monId..", cityIdx="..cityCfg.cityIdx)

	local fubenPtr 			= Actor.getFubenPrt( monster )				--怪物所在副本
	local fubenHandle 		= Fuben.getFubenHandle( fubenPtr )
	local GetBossNumFunc 	= MagicCityGetMonsterNumFunc( cityCfg )

	local actorId 	= Fuben.getOwnerId( fubenPtr )
	local actorPtr 	= Actor.getActorById( actorId )
	--print("OnMagicCityBabyDie , actorId="..actorId)
	if actorPtr and IsInMagicCityFuben( actorPtr ) then 			--玩家在线并且在副本中
		OnMagicCityOver( actorPtr, cityCfg, 0 ) 					--通关失败
		Fuben.setFubenTime( fubenHandle, 1 )						--关闭副本
	end
end


--[[
迷幻魔宫通关成功(手工打，非扫荡)
]]
function OnMagicCityOver( sysarg, cityCfg, sts )
	--print("OnMagicCityOver , cityCfg="..sts)
	local panelInfo = {}
	panelInfo.subActivityId = cityCfg.cityIdx
	panelInfo.sts 		= sts
	if sts > 0 then
		local sVar = Actor.getStaticVar(sysarg)
		local now  = System.getCurrMiniTime()
		panelInfo.passTime 	= now - sVar.magicCityeEnterTime
		if panelInfo.passTime < 0 then
			panelInfo.passTime = 0
		end
		local newStar  = MakeMagicCityStar( cityCfg.star, panelInfo.passTime ) 			--计算通关星级
		local newScore = MakeMagicCityScore( cityCfg.score, panelInfo.passTime )		--计算通关评分

		local oldStar = GetMagicCityMyValue( sysarg, cityCfg.cityIdx, MAGICCITY_MY_MAX_STAR ) 
		if newStar > oldStar then
			SetMagicCityMyValue( sysarg, cityCfg.cityIdx, MAGICCITY_MY_MAX_STAR, newStar ) 					--设置最大星级
		end
		SetMagicCityMyValue( sysarg, cityCfg.cityIdx, MAGICCITY_MY_PASS_SCORE, newScore ) 					--设置上次通关评分
		SetMagicCityMyValue( sysarg, cityCfg.cityIdx, MAGICCITY_MY_PASS_TIME, panelInfo.passTime ) 			--设置上次通关时间

		panelInfo.star = newStar
		ProcMagicCityWeekScoreRank( sysarg, cityCfg.cityIdx, panelInfo.passTime,  newScore, 1 )				--处理评分排行榜

		GiveMagicCityPassAwards( sysarg, cityCfg.cityIdx, newStar, 1 ) 						--通关奖励(单倍)
		GiveMagicCityFirstFullStarAwards( sysarg, cityCfg.cityIdx, newStar )				--首次三星通关奖励
	end
	PassActivityRightPanel( sysarg, 1, enRightPanelActivity_MagicCity, panelInfo )
	SendMagicCityMyData( sysarg, cityCfg.cityIdx )

	Actor.exitFuben( sysarg )						--打完退出
end


--[[
设置周榜和楼主，
扫荡只给积分到周榜，不算楼主
byHand:1-手工打，0-扫荡
]]
function ProcMagicCityWeekScoreRank( sysarg, cityIdx, passTime, score, byHand  )
	local actorId 	= Actor.getActorId( sysarg )
	local job 		= Actor.getIntProperty( sysarg, PROP_ACTOR_VOCATION )
	UpdateCommonRankValueById( actorId, MagicCityWeekRank, score )				--积分累加
	SetCommonRankColumnValueById(actorId, MagicCityWeekRank, 0, 0,  Actor.getName(sysarg) )
	SetCommonRankColumnValueById(actorId, MagicCityWeekRank, 0, 1,  0 )			--留空，无意义
	SetCommonRankColumnValueById(actorId, MagicCityWeekRank, 0, 2,  job )

	local ownerId 		= GetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_ID )
	local ownerPassTime = GetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_PASS_TIME )
	--print("ProcMagicCityWeekScoreRank, passTime="..passTime..", score="..score..", ownerId="..ownerId..", ownerPassTime="..ownerPassTime)
	if byHand > 0 and ( ownerId == 0 or ownerPassTime <= 0 or passTime > 0 and passTime < ownerPassTime ) then   --没有楼主或者时间更少
		--print("HandleMagicCityOp, byHand="..byHand)
		ClearMagicCityOwner( actorId )					--清除该玩家的楼主信息

		SetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_ID, actorId )
		SetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_NAME, 	Actor.getName(sysarg)  )
		SetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_PASS_TIME, passTime )

		SendMagicCityOwnerData( sysarg )
	end
end

--[[
清除该玩家的楼主信息
]]
function ClearMagicCityOwner( actorId )
	for cityIdx, cityCfg in ipairs( MagicCityCfg.cities ) do
		local ownerId = GetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_ID )
		if ownerId > 0 and ownerId == actorId then
			SetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_ID, 0 )
			SetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_NAME, 	""  )
			SetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_PASS_TIME, 0 )
		end
	end
end

--评定星级
function MakeMagicCityStar( starRule, passTime )
	if not starRule then
		return 0
	end

	if passTime <= 1 then 	--通关时间绝对没可能少到这种程度
		return 0
	end

	local star = 0
	for k, needTime in pairs( starRule ) do
		if passTime <= needTime then
			star = k
		end
	end
	return star
end

--计算通关积分
function MakeMagicCityScore( scoreRule, passTime )
	if not scoreRule then
		return 0
	end

	if passTime <= 1 then 	--通关时间绝对没可能少到这种程度
		return 0
	end

	local elem = GetElemByCond( scoreRule, passTime )
	return elem.score or 0
end

function HandleMagicCityOp( sysarg, packet )
	local cityIdx  = DataPack.readChar(packet)
	local opType   = DataPack.readChar(packet)
	local opParam  = DataPack.readChar(packet)
	--print("HandleMagicCityOp, cityIdx="..cityIdx..", opType="..opType..", opParam="..opParam)
	if opType == 1 then
		EnterMagicCity( sysarg, cityIdx )
	elseif opType == 2 then
		SweepMagicCity( sysarg, cityIdx, opParam )
	elseif opType == 3 then
		BuyMagicCityEnterTimes( sysarg, cityIdx )
	end
end

--[[副本扫荡]]
function SweepMagicCity( sysarg, cityIdx, num )
	local cityCfg = GetMagicCityCfgByCityIdx( cityIdx )
	if not cityCfg then
		return
	end

	if num < 1 then
		return
	end

	--开服天数未到，不能扫荡
	if not CheckOpenServerDay( cityCfg ) then
		Actor.sendTipmsg( sysarg, Lang.ScriptTips.COM0076, ttFlyTip )
		return
	end

	local maxStar = GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_MAX_STAR )
	--print("SweepMagicCity, cityIdx="..cityIdx..", num="..num..", maxStar="..maxStar)
	local fullStar = 3
	if maxStar < fullStar then
		Actor.sendTipmsg( sysarg, Lang.ScriptTips.MagicCity003,ttFlyTip )
		return
	end

	if not CheckActorDailyDoneTimes( sysarg, enDailyOpTimes_MagicCity, cityIdx, num ) then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0075,ttFlyTip)
		return false
	end

	if not CheckConsumeCond( sysarg, cityCfg.sweepConsumes, num ) then
		return
	end

	if not DoConsumeCond( sysarg, cityCfg.sweepConsumes, num, GameLog.clMagicCitySweepFee, Lang.ScriptTips.MagicCityLog04 ) then
		return
	end

	AddActorDailyDoneTimes( sysarg, enDailyOpTimes_MagicCity, cityIdx, num ) 				--进入次数+num
	SendMagicCityMyEnterTimes( sysarg )

	--取上次通关时间和评分，设置周榜
	local lastPassTime  = GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_PASS_TIME )
	local lastPassScore = GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_PASS_SCORE )
	ProcMagicCityWeekScoreRank( sysarg, cityCfg.cityIdx, lastPassTime,  lastPassScore * num, 0 )		--处理评分排行榜

	GiveMagicCityPassAwards( sysarg, cityIdx, maxStar, num )			--给予通关奖励

	local msg = string.format( Lang.ScriptTips.MagicCity005, cityCfg.cityName, num )
	Actor.sendTipmsg( sysarg, msg, ttFlyTip )

	--print("SweepMagicCity, cityIdx="..cityIdx..", num="..num)
	Actor.triggerAchieveEvent(sysarg, aAchieveEventFinishActivity, 12, num)			--参加魔域迷城N次
	Actor.triggerQuestEvent(sysarg, 45, 8, num) 									--任务事件-参加魔域迷城N次
end

--[[
给予通关奖励
]]
function CheckMagicCityPassAwards( sysarg, star )
	local cityCfg = GetMagicCityCfgByCityIdx( cityIdx )
	if not cityCfg then
		return false
	end

	local awards = cityCfg.starAwards[star]
	if awards then
		return false
	end

	return IsBagGridEnough( sysarg, awards )
end


--[[
给予通关奖励
]]
function GiveMagicCityPassAwards( sysarg, cityIdx, star, num )
	--print("GiveMagicCityPassAwards, cityIdx="..cityIdx..", star="..star)
	local cityCfg = GetMagicCityCfgByCityIdx( cityIdx )
	if not cityCfg then
		return
	end

	local awards = cityCfg.starAwards[star]
	if not awards then
		return
	end

	local myRewards = GetAwardsByRate( awards, num )		--N倍
	if IsBagGridEnough( sysarg, myRewards ) then
		GiveCommonAward(sysarg, myRewards, GameLog.clMagicCityPassAwars, Lang.ScriptTips.MagicCityLog05)
	else
		--print("GiveMagicCityPassAwards, send mail")
		local actorId 	= Actor.getActorId( sysarg )
		local title 	= Lang.ScriptTips.MagicCityMailTitle02
		local content 	= string.format( Lang.ScriptTips.MagicCityMailContent02,  cityCfg.cityName, star )
		Awards.GiveToMailById( actorId, myRewards, title, content, GameLog.clMagicCityPassAwars, Lang.ScriptTips.MagicCityLog05 )
	end
end

--[[
给予首次三星通关奖励
]]
function GiveMagicCityFirstFullStarAwards( sysarg, cityIdx, star )
	if star < 3 then
		return
	end

	local isFirstFull = GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_FIRSTFULLPASS )
	--print("BuyMagicCityEnterTimes, cityIdx="..cityIdx..", isFirstFull="..isFirstFull)
	if isFirstFull > 0 then
		return
	end

	local cityCfg = GetMagicCityCfgByCityIdx( cityIdx )
	if not cityCfg then
		return
	end

	local awards = cityCfg.firstFullStarAwards
	if not awards then
		return
	end

	SetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_FIRSTFULLPASS, 1 )   	--设置已经领取首次三星通关奖励
	
	local actorId 	= Actor.getActorId( sysarg )
	local title 	= Lang.ScriptTips.MagicCityMailTitle03
	local content 	= string.format( Lang.ScriptTips.MagicCityMailContent03,  cityCfg.cityName )
	Awards.GiveToMailById( actorId, awards, title, content, GameLog.clMagicCityFirstFullStartAwars, Lang.ScriptTips.MagicCityLog06 )

	--[[
	if IsBagGridEnough( sysarg, awards ) then
		GiveCommonAward(sysarg, awards, GameLog.clMagicCityFirstFullStartAwars, Lang.ScriptTips.MagicCityLog06)
	else
		--print("GiveMagicCityFirstFullStarAwards, send mail")
		local actorId 	= Actor.getActorId( sysarg )
		local title 	= Lang.ScriptTips.MagicCityMailTitle03
		local content 	= string.format( Lang.ScriptTips.MagicCityMailContent03,  cityCfg.cityName )
		Awards.GiveToMailById( actorId, awards, title, content, GameLog.clMagicCityFirstFullStartAwars, Lang.ScriptTips.MagicCityLog06 )
	end
	]]
end

--[[
给予楼主奖励
每天0点发奖，发奖后请空
]]
function SendMagicCityOwnerAwards()
	for cityIdx, cityCfg in ipairs( MagicCityCfg.cities ) do
		local ownerId   = GetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_ID )
		local ownerName = GetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_NAME )
		--print("SendMagicCityOwnerAwards, cityIdx="..cityIdx..", ownerId="..ownerId..", ownerName="..ownerName)
		if ownerId > 0 then
			local title 	= Lang.ScriptTips.MagicCityMailTitle04
			local content 	= string.format( Lang.ScriptTips.MagicCityMailContent04,  cityCfg.cityName )
			Awards.GiveToMailById( ownerId, cityCfg.cityOwnerAwards, title, content, GameLog.clMagicCityOwnerAwards, Lang.ScriptTips.MagicCityLog07 )
		end
	end

	local sVar = System.getStaticVar()
	sVar.magicCityOwnerData = nil
end



function BuyMagicCityEnterTimes( sysarg, cityIdx )
	--print("BuyMagicCityEnterTimes, cityIdx="..cityIdx)
	local cityCfg = GetMagicCityCfgByCityIdx( cityIdx )
	if not cityCfg then
		return
	end

	--开服天数未到，不能购买
	if not CheckOpenServerDay( cityCfg ) then
		Actor.sendTipmsg( sysarg, Lang.ScriptTips.COM0076, ttFlyTip )
		return
	end

	local sVar = Actor.getStaticVar(sysarg)
	if not sVar.magicCityData then
		sVar.magicCityData = {}
	end

	if not sVar.magicCityData[cityIdx] then
		sVar.magicCityData[cityIdx] = {}
	end

	local buyTimes 	= GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_BUY_TIMES ) 	--已经购买次数
	if buyTimes >= cityCfg.dailyBuyTimes then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.MagicCity002,ttFlyTip)
		return
	end

	local newBuyTimes = buyTimes+1
	local buyConsume = cityCfg.buyEnterTimesConsumes[newBuyTimes]
	if not buyConsume then
		return false
	end

	local buyConsumes = { buyConsume }
	if not CheckConsumeCond( sysarg, buyConsumes, 1 ) then
		return false
	end

	if not DoConsumeCond( sysarg, buyConsumes, 1, GameLog.clMagicCityBuyEnterTimesFee, Lang.ScriptTips.MagicCityLog02 ) then
		return false
	end

	SetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_BUY_TIMES, newBuyTimes )
	SendMagicCityMyEnterTimes( sysarg )
end

function HandleSendMagicCityMyEnterTimes( sysarg )
	SendMagicCityOwnerData( sysarg )
	SendMagicCityMyEnterTimes( sysarg )
end

function SendMagicCityOwnerData( sysarg )
	local pack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sMagicCitySendOwnerData)
    if pack then
    	DataPack.writeByte(pack, #MagicCityCfg.cities )
    	for cityIdx, cityCfg in ipairs( MagicCityCfg.cities ) do
        	local ownerName = GetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_NAME )
			local passTime 	= GetMagicCityOwnerValue( sysarg, cityIdx, MAGICCITY_OWNER_PASS_TIME )
			local maxStar 	= GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_MAX_STAR )

        	DataPack.writeByte(pack, cityIdx)
       	 	DataPack.writeString(pack, ownerName)
			DataPack.writeUInt(pack, passTime)
        	DataPack.writeByte(pack, maxStar)
       		--print("SendMagicCityOwnerData, cityIdx="..cityIdx..", ownerName="..ownerName..", passTime="..passTime..", maxStar="..maxStar)
       	end
       	DataPack.flush(pack)
    end
end

function SendMagicCityMyEnterTimes( sysarg )
	local pack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sMagicCitySendMyEnterTimes)
    if pack then
    	DataPack.writeByte(pack, #MagicCityCfg.cities )
    	for cityIdx, cityCfg in ipairs( MagicCityCfg.cities ) do
        	local doneTimes = GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_DONE_TIMES )
			local buyTimes 	= GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_BUY_TIMES )	
			local maxTimes 	= buyTimes + cityCfg.dailyEnterTimes

        	DataPack.writeByte(pack, cityIdx)
			DataPack.writeByte(pack, doneTimes)
        	DataPack.writeByte(pack, maxTimes)
        	DataPack.writeByte(pack, buyTimes)
       		--print("SendMagicCityMyEnterTimes, cityIdx="..cityIdx..", doneTimes="..doneTimes..", maxTimes="..maxTimes..", buyTimes="..buyTimes)
       	end
       	DataPack.flush(pack)
    end
end

function HandleSendMagicCityMyData( sysarg, packet )
	local cityIdx = DataPack.readChar(packet)
	SendMagicCityMyData( sysarg, cityIdx )
end

--[[
发送本人闯关数据
]]
function SendMagicCityMyData( sysarg, cityIdx )
	--print("SendMagicCityMyData, cityIdx="..cityIdx)
	local cityCfg = GetMagicCityCfgByCityIdx( cityIdx )
	if not cityCfg then
		return
	end

	local pack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sMagicCitySendMyData)
    if pack then
    	local maxStar 	= GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_MAX_STAR )
		local passTime 	= GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_PASS_TIME )
		local passScore = GetMagicCityMyValue( sysarg, cityIdx, MAGICCITY_MY_PASS_SCORE )

        DataPack.writeByte(pack, cityIdx)
        DataPack.writeByte(pack, maxStar)
		DataPack.writeUInt(pack, passTime)
        DataPack.writeShort(pack, passScore)
        DataPack.flush(pack)
        --print("SendMagicCityMyData, cityIdx="..cityIdx..", maxStar="..maxStar..", passTime="..passTime..", passScore="..passScore)
    end
end

--[[
获取魔域迷城本人的某个数值
]]
function GetMagicCityMyValue( sysarg, cityIdx, valueIdx )
	local sVar = Actor.getStaticVar(sysarg)
	if not sVar.magicCityData then
		sVar.magicCityData = {}
	end

	if not sVar.magicCityData[cityIdx] then
		sVar.magicCityData[cityIdx] = {}
	end

	return sVar.magicCityData[cityIdx][valueIdx] or 0
end

function SetMagicCityMyValue( sysarg, cityIdx, valueIdx, newValue )
	local sVar = Actor.getStaticVar(sysarg)
	if not sVar.magicCityData then
		sVar.magicCityData = {}
	end

	if not sVar.magicCityData[cityIdx] then
		sVar.magicCityData[cityIdx] = {}
	end

	sVar.magicCityData[cityIdx][valueIdx] = newValue
end

--[[
获取魔域迷城楼主的某个数值
]]
function GetMagicCityOwnerValue( sysarg, cityIdx, valueIdx )
	local sVar = System.getStaticVar()
	if not sVar.magicCityOwnerData then
		sVar.magicCityOwnerData = {}
	end

	if not sVar.magicCityOwnerData[cityIdx] then
		sVar.magicCityOwnerData[cityIdx] = {}
	end

	if valueIdx ~= MAGICCITY_OWNER_NAME then
		return sVar.magicCityOwnerData[cityIdx][valueIdx] or 0
	else
		return sVar.magicCityOwnerData[cityIdx][valueIdx] or ""
	end
end

--[[
设置魔域迷城楼主的某个数值
]]
function SetMagicCityOwnerValue( sysarg, cityIdx, valueIdx, newValue )
	local sVar = System.getStaticVar()
	if not sVar.magicCityOwnerData then
		sVar.magicCityOwnerData = {}
	end

	if not sVar.magicCityOwnerData[cityIdx] then
		sVar.magicCityOwnerData[cityIdx] = {}
	end

	sVar.magicCityOwnerData[cityIdx][valueIdx] = newValue
end


InitMagicCityWeekRank()
ResisterMagicCityProc()
